package com.aotuman.ktcoroutineandroid.chapter.javademo;

import org.jetbrains.annotations.NotNull;

import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import kotlin.coroutines.EmptyCoroutineContext;
import kotlin.coroutines.intrinsics.IntrinsicsKt;

public class BaseContinuationImpl implements Continuation<Object> {

    private final Continuation<Object> completion;

    public static final Object COROUTINE_SUSPENDED = IntrinsicsKt.getCOROUTINE_SUSPENDED();

    public BaseContinuationImpl(Continuation<Object> completion) {
        this.completion = completion;
    }

    @NotNull
    @Override
    public CoroutineContext getContext() {
        return EmptyCoroutineContext.INSTANCE;
    }

    @Override
    public void resumeWith(@NotNull Object result) {
        try {
            BaseContinuationImpl current = this;
            Object param = result;
            while (true) {
                Object outcome = invokeSuspend(param);
                if (outcome == COROUTINE_SUSPENDED) return;
                if (completion instanceof BaseContinuationImpl) {
                    current = (BaseContinuationImpl) completion;
                    param = outcome;
                } else {
                    completion.resumeWith(outcome);
                    return;
                }
            }
        } catch (Exception e) {
            completion.resumeWith(e);
        }
    }

    protected Object invokeSuspend(Object result) {
        return null;
    }
}